﻿// jqDrag 拖拽方法
// this:拖拽的对象
// h:触发拖拽事件的对象
(function($) {
    $.fn.jqDrag = function(h) { return i(this, h, 'd'); };
    $.fn.jqResize = function(h) { return i(this, h, 'r'); };
    $.jqDnR = { 
        dnr: {}, 
        e: 0,
        drag: function(v) {
            if (M.k == 'd') E.css({ left: M.X + v.pageX - M.pX, top: M.Y + v.pageY - M.pY });
            else E.css({ width: Math.max(v.pageX - M.pX + M.W, 0), height: Math.max(v.pageY - M.pY + M.H, 0) });
            return false;
        },
        stop: function() { E.css('opacity', M.o); $(document).unbind('mousemove', J.drag).unbind('mouseup', J.stop); }
    };
    var J = $.jqDnR, M = J.dnr, E = J.e,
    i = function(e, h, k) { 
	    	return e.each(function() {
	        h = (h) ? $(h, e) : e;
	        h.unbind("mousedown").bind('mousedown', { e: e, k: k }, function(v) {
	            var d = v.data, p = {}; E = d.e;
	            // attempt utilization of dimensions plugin to fix IE issues
	            if (E.css('position') != 'relative') { try { E.position(p); } catch (e) { } }
	            M = { X: p.left || f('left') || 0, Y: p.top || f('top') || 0, W: f('width') || E[0].scrollWidth || 0, H: f('height') || E[0].scrollHeight || 0, pX: v.pageX, pY: v.pageY, k: d.k };
	            $(document).unbind("mousemove").mousemove($.jqDnR.drag).unbind("mouseup").mouseup($.jqDnR.stop);
	            return false;
	        });
	    });
	},
	f = function(k) { return parseInt(E.css(k)) || false; };
})(jQuery);

//用于iframe加载完成后的全局回调
popuOnShowFn = function () { };

var pop_z_index = 100000;
// jqPopU 弹窗体系
function PopU() {
    this.keyIsESC = 27;
    this.keyIsEnter = 13;
    this.keyIsSpace = 32;
    this.timerClosePop = null;
    this.initTop = null;
    this.z_index = pop_z_index;
    this.closeIsHide = false;
    //对象化核心部件
    this.pubOverlay = null;//遮罩层
    this.pubWindow = null;//弹窗对象
    this.pubContent = null;//传入显示内容
    this.pubLoading = null;//加载信息
    this.pubBtnList = null;//按钮容器
    this.pubTipsAtObj = null; //弹窗跟随对象
    this.ShowCloseBtn = true;
    //公共调用方法
    ie6 = false;// $.browser.msie && ($.browser.version == "6.0")
    //初始化
    this._initialize();
};
PopU.prototype._initialize = function() {
    var $this = this;
    //$(document).bind("keydown", function(e) { $this.fnKeyDown(e); });
    //处理IE6下滚动时的定位
//    if ($.browser.version == "6.0") {
//        $(window).bind("scroll", function() {
//            if (toolTmp.initTop == null) toolTmp.initTop = 150;
//                var topscroll = parseInt(document.documentElement.scrollTop || document.body.scrollTop,10);
//            $("#popWindow").css("top", parseInt(toolTmp.initTop,10) + topscroll);
//            $("#popConfirm").css("top", parseInt(toolTmp.initTop,10) + topscroll);
//            $("#popAlert").css("top", parseInt(toolTmp.initTop,10) + topscroll);
//        });
//    }
}
//定义窗口方法
PopU.prototype.init = function (param) {
    //当弹窗对象存在而且设置不需缓存时 清理对象
    if (this.pubWindow && !this.closeIsHide) {
        this.pubOverlay = null; //遮罩层
        this.pubWindow = null; //弹窗对象
        this.pubContent = null; //传入显示内容
        this.pubLoading = null; //加载信息
        this.pubBtnList = null; //按钮容器
        this.pubTipsAtObj = null; //弹窗跟随对象
    }
    var $this = this;
    if (undefined == param.onYesFn || typeof (param.onYesFn) != "function")
        param.onYesFn = function () { };
    else
        param.ShowYesBtn = true;
    if (undefined == param.onNoFn || typeof (param.onNoFn) != "function")
        param.onNoFn = function () { };
    else
        param.ShowNoBtn = true;

    if (undefined == param.onShowFn || typeof (param.onShowFn) != "function") param.onShowFn = function () { }; //显示完成后执行回调
    if (undefined == param.onLoadFn || typeof (param.onLoadFn) != "function") param.onLoadFn = function () { }; //调用开始时执行回调
    if (undefined == param.onHideFn || typeof (param.onHideFn) != "function") param.onHideFn = function () { }; //关闭或隐藏时执行回调

    param = $.extend(true, {
        ShowYesBtn: false, //是否显示确认按钮
        ShowYesBtnValue: '确定',
        ShowNoBtn: false, //是否显示取消按钮
        ShowNoBtnValue: '取消',
        headClass: '',
        w: 240, //弹窗宽度
        h: 0, //弹窗高度
        showOverlay: true, //是否显示遮罩层
        overlayParam: 50, //遮罩层透明度[0-100] (0为透明 但是有这一层)
        onOverlay: 0, //遮罩层事件 (0:点击遮罩层时窗口闪烁 1:点击遮罩层时窗口关闭 2:mouseover遮罩层时窗口关闭)
        autoClose: false, //是否自动关闭
        closeTime: 2000, //自动关闭时间 (单位毫秒 0为不关闭)
        closeIsHide: false, //关闭时是否只是隐藏对象而不是移除对象
        tipsAtObj: false, //悬浮紧跟对象
        offsetX: 0, // 相对偏移量X值
        offsetY: 0, // 相对偏移量Y值
        title: "", //标题栏信息
        contents: "", //显示内容绑定
        type: "string", //传入的Contents的类型 ("string":字符串,"jquery":JQ对象,"iframe":框架页面URL,"ajax":异步请求页面URL)
        drag: false, //窗口支持拖拽
        tip: "",
        btnList: new Array()//窗口系统按钮列表
    }, param);

    if (undefined == param.x) //弹窗x坐标
        param.x = this.getInnerW() / 2 - param.w / 2;
    if (undefined == param.y) { //弹窗y坐标
        var popHeight = param.h + 46; //46px是边框高度加各级内边距
        if (param.title.length > 0) popHeight += 32; //32px为标题栏高度
        if (param.ShowNoBtn || param.ShowYesBtn) popHeight += 32; //32px为底部按钮拦高度
        param.y = this.getScrollTop() + parseInt(this.getInnerH() * 0.6 / 2 - popHeight / 2);
        if (param.y < 50) param.y = 50;
    }
    if (param.tipsAtObj) {
        this.pubTipsAtObj = param.tipsAtobj;
        //粘的方向要继续做调整
        param.x = this.getOffsetL(param.tipsAtObj, param.offsetX);
        param.y = this.getOffsetT(param.tipsAtObj, param.offsetY);
    }
    this.closeIsHide = param.closeIsHide;
    //var scrollTop = document.documentElement.scrollTop;

    /* 对象化输出 --------------------------- */
    //this.z_index += 4;
    pop_z_index += 10;

    this.pubWindow = $('<div class="popU" style="left:' + param.x + 'px;top:' + param.y + 'px;width:' + param.w + 'px;z-index:' + (this.z_index - 1) + '"></div>'); //整个弹窗对象
    if (ie6) {
        this.pubWindow.append('<iframe class="popU_ifr6" frameborder="0" scrolling="no" src="" style=" z-index:' + (this.z_index - 2) + '"></iframe>');
    }
    this.pubOverlay = $('<div class="popU_Overlay"></div>').css({ position: ie6 ? 'absolute' : 'fixed', zIndex: (this.z_index - 3), opacity: param.overlayParam / 100 });
    if (!param.showOverlay)
        this.pubOverlay.css({ width: "0px", height: "0px" });
    var popHtml;
    popHtml = new Array();
    popHtml.push('        <div class="popU_L">');
    popHtml.push('            <div class="popU_R">');
    popHtml.push('                <div class="popU_Rin BgColor"></div>');
    popHtml.push('                <div class="popU_Main '+ param.headClass +'">');
    popHtml.push('                    <div class="popU_Btn"></div>');
    popHtml.push('                    <div class="hd"></div>');
    popHtml.push('                    <div class="bd popBd clearfix" style="position:relative; ' + (param.h) + '"></div>');
    popHtml.push('                    <div class="ft clearfix"></div>');
    popHtml.push('                </div>');
    popHtml.push('            </div>');
    popHtml.push('        </div>');
    var popU_Box = $(popHtml.join('')); //外框对象
    this.pubWindow.append(popU_Box);

    this.pubBtnList = this.pubWindow.find(".popU_Btn").css("z-index", this.z_index);
    var popU_Main = this.pubWindow.find(".popU_Main"); //内框对象
    if (param.title.length > 0)
        popU_Main.find(".hd").html(param.title);
    else
        popU_Main.find(".hd").addClass("emptyHd");
    if (param.drag) {
        popU_Main.find(".hd").css("cursor", "move");
        this.pubWindow.jqDrag(popU_Main.find(".hd"));
    }
    if (param.h > 0) {
        popU_Main.find(".popBd").css({ height: (param.h + 20) + "px", "overflow-x": "hidden", "overflow-y": "auto" });
    }
    //填充传入系统按钮
    $.each(param.btnList, function (i, item) {
        popU_Main.find(".popU_Btn").append(item);
    });

    //填充传入内容
    switch (param.type) {
        case "string":
            this.pubContent = $(popU_Main.find("div.popBd"));
            this.pubContent.append(param.contents);
            break;
        case "jquery":
        case "div":
            this.pubContent = $(param.contents);
            if (this.pubContent.hasClass("bd") || this.pubContent.find("div.bd").length > 0)
                popU_Main.find("div.popBd").replaceWith(this.pubContent.addClass("clearfix"));
            else
                popU_Main.find("div.popBd").append(this.pubContent);
            break;
        case "iframe":
            this.pubLoading = $("<div id='popWindowLoading' style='margin: 0pt; padding: 0pt; width: 100%; height: 100%;'>&nbsp;</div>");
            this.pubContent = $("<iframe id='popIframe' name='popuIframe' style='width: 100%; height: " + param.h + "px;' scrolling='auto' frameborder='0' onload='popuOnShowFn()' rel='" + param.contents + "' src='javascript:;'></iframe>");
            //将回调事件            
            popuOnShowFn = param.onShowFn;
            popU_Main.find("div.popBd").append(this.pubContent);
            break;
        case "ajax":
            popU_Main.find("div.popBd").append("暂不支持AJAX类型内容");
            break;
    }
    if (param.tip && param.tip != "") {
        popU_Main.find("div.ft").append("<span class='tip'>" + param.tip + "</span>");
    }
    //填充确认或取消按钮
    if (param.ShowYesBtn) {
        popU_Main.find("div.ft").append("<input type='button' class='btn btn-default btn-primary PopU_BtnYes' value='" + param.ShowYesBtnValue + "' />");
        popU_Main.find(".PopU_BtnYes").bind("click", function () {
            param.onYesFn(); // $this.close();
        });
    }
    if (param.ShowNoBtn) {
        popU_Main.find("div.ft").append("&nbsp;&nbsp;<input type='button' class='btn btn-default PopU_BtnNo' value='" + param.ShowNoBtnValue + "' />");
        popU_Main.find(".PopU_BtnNo").bind("click", function () { param.onNoFn(); $this.close(); });
    }
    //遮罩层事件
    if (param.onOverlay == 0)
        this.pubOverlay.bind("click", function () { $this.flash(); });
    else if (param.onOverlay == 1)
        this.pubOverlay.bind("click", function () { $this.close(); });
    else if (param.onOverlay == 2)
        this.pubOverlay.hover(function () { }, function () { $this.close(); });
    //自动关闭事件
    if (param.autoClose && param.closeTime > 0)
        this.timerClosePop = window.setTimeout(function () { $this.close(); }, param.closeTime);
}
//窗口定义方法
PopU.prototype.initPop = function (param) {
    var $this = this;
    param = $.extend(true, { btnList: new Array() }, param); //窗口系统按钮列表
    if (param.ShowCloseBtn !== false) {
        //添加关闭按钮
        var btnClose = $("<div class='btnClose'><a class='close' href='javascript:void(0);' title='关闭'></a></div>");
        if (undefined == param.onHideFn || typeof (param.onHideFn) != "function") {
            btnClose.bind("click", function () { $this.close(); });
        }
        else {
            btnClose.bind("click", function () { $this.close(); param.onHideFn(); });
        }
        param.btnList.push(btnClose);
    }
    //调用定义方法
    this.init(param);
    //添加到页面
    this.pubWindow.hide();
    this.pubWindow.appendTo(document.body);
    this.pubOverlay.hide();
    this.pubOverlay.appendTo(document.body);
}
//显示窗口方法
PopU.prototype.showPop = function () {
    var $this = this;
    if (this.pubTipsAtObj) {
        var x = this.getOffsetL(this.pubTipsAtObj, param.offsetX);
        var y = this.getOffsetT(this.pubTipsAtObj, param.offsetY);
        this.pubWindow.css({ left: x + "px", top: y + "px" });
    }
    var iframe = this.pubWindow.find("#popIframe");
    if (iframe.length > 0)
        iframe.attr("src", iframe.attr("rel")).removeAttr("rel");
    if (this.pubWindow.find("div.ft").length>0 && this.pubWindow.find("div.ft").html() == "")
        this.pubWindow.find("div.ft").remove();
    this.pubWindow.show();
    this.pubWindow.focus(); //取得焦点
    this.pubOverlay.show();
}
//提示方法
PopU.prototype.alert = function(param) {
    var $this = this;
    param = $.extend(true, {
        overlayParam: 0,
        closeIsHide: false,//坚决不缓存窗口 避免重复定义
        onNoFn: null //屏蔽取消按钮
    },param);
    param.ShowNoBtn = false; //屏蔽取消按钮
    param.showOverlay = true; //强制开启遮罩层
    if (undefined == param.onYesFn || typeof (param.onYesFn) != "function")
    {
        param.onOverlay = 1;//点击遮罩层则关闭窗口
        if(undefined == param.title && undefined == param.autoClose)
        {
            //若不定义标题栏也不定义自动关闭 则自动关闭 默认关闭时间为两秒
            param.autoClose = true;
        }
    }
    else
        param.onOverlay = 0;//点击遮罩层则弹窗闪烁
    //调用定义方法
    this.init(param);
    //显示到页面
    this.pubWindow.appendTo(document.body);
    this.pubWindow.show();
    this.pubWindow.find(".PopU_BtnYes").focus();//给确认按钮加焦点
    this.pubOverlay.appendTo(document.body);
    this.pubOverlay.show();
}
//确认方法
PopU.prototype.confirm = function(param) {
    var $this = this;
    param = $.extend(true, { overlayParam: 0 }, param);
    param.closeIsHide = false; //坚决不缓存窗口 避免重复定义
    param.ShowNoBtn = true; //显示确认按钮
    param.ShowYesBtn = true; //显示取消按钮
    param.showOverlay = true; //强制开启遮罩层
    //调用定义方法
    this.init(param);
    //显示到页面
    this.pubWindow.appendTo(document.body);
    this.pubWindow.show();
    this.pubWindow.find(".PopU_BtnYes").focus();//给确认按钮加焦点
    this.pubOverlay.appendTo(document.body);
    this.pubOverlay.show();
}
//关闭方法
PopU.prototype.close = function () {
    var $this = this;
    //清除自动关闭事件
    if ($this.timerClosePop != null)
        window.clearTimeout($this.timerClosePop);
    //判断关闭或隐藏
    if (this.closeIsHide) {
        $this.pubWindow.hide();
        $this.pubOverlay.hide();
    }
    else {
        $this.pubWindow.remove();
        $this.pubOverlay.remove();
    }
}

// 点击非弹窗区域时 提示用户关注弹出窗口
PopU.prototype.flash=function() {
    var $this = this;
    setTimeout( function(){ $this.pubWindow.find(".hd").addClass('flash') }, 50);
    setTimeout( function(){ $this.pubWindow.find(".hd").removeClass('flash') }, 80);
    setTimeout( function(){ $this.pubWindow.find(".hd").addClass('flash') }, 150);
    setTimeout( function(){ $this.pubWindow.find(".hd").removeClass('flash') }, 180);
}
///键盘控制
PopU.prototype.fnKeyDown = function(keyEvent) {
    //debugger;
    if (!keyEvent) keyEvent = window.event;
    var kc = keyEvent.which || keyEvent.keyCode;
    if (kc == this.keyIsESC) {
        var isKey = true;
        this.close(isKey);
    }
}
// 设置弹出层跟随对象显示并计算相对位置
PopU.prototype.getOffsetL=function(obj, positionNum) {
    var jqObj = $(obj);
    obj = jqObj[0];
    var x = obj.offsetLeft;
    while (obj = obj.offsetParent) x += obj.offsetLeft;
    return x + positionNum;
}
// 设置弹出层跟随对象显示并计算相对位置
PopU.prototype.getOffsetT=function(obj, positionNum) {
    var $obj = $(obj);
    obj = $obj[0];
    var y = obj.offsetTop;
    while (obj = obj.offsetParent) y += obj.offsetTop;
    y += $obj.height();
    return y + positionNum;
}
//获得卷屏高度
PopU.prototype.getScrollTop=function() {
    var scrollTop=0;
    if(document.documentElement && document.documentElement.scrollTop)
        scrollTop=document.documentElement.scrollTop;
    else if(document.body)
        scrollTop=document.body.scrollTop;
    return scrollTop;
}
//取得页面在当前屏幕内可视区域的宽度
PopU.prototype.getInnerW=function() {
    return (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth;
}
//取得页面在当前屏幕内可视区域的高度
PopU.prototype.getInnerH=function() {
    return (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
}

var _publicConfirm = new PopU();
popuConfirm = function (param) {
    if (_publicConfirm.isShow)
        _publicConfirm.close();
    _publicConfirm.confirm(param);
};
closeConfirm = function () {
    _publicConfirm.close();
};

var _publicAlert = new PopU();
popuAlert = function (param) {
    //关闭已经打开的对象
    if (_publicAlert.isShow)
        _publicAlert.close();
    //确保在全局处不出现冲突
    _publicAlert.alert(param);
};
closeAlert = function () {
    _publicAlert.close();
};